package com.ruoyi.framework.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "delFlag", String.class, "0");
        this.strictInsertFill(metaObject, "createNo", String.class, getUserName());
        this.strictInsertFill(metaObject, "createBy", String.class, getUserName());
        this.strictInsertFill(metaObject, "deptId", Long.class, getDeptId());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "updateNo", String.class, getUserName());
        this.strictInsertFill(metaObject, "updateBy", String.class, getUserName());
    }

    /**
     * 获取部门ID
     * @return
     */
    private Long getDeptId() {
        Long deptId = SecurityUtils.getLoginUser().getDeptId();
        if (deptId == null) {
            return 100L;
        }
        return deptId;
    }

    private String getUserName() {
        String username = SecurityUtils.getLoginUser().getUsername();
        if (username == null) {
            return "admin";
        }
        return username;
    }
}
